using System.Text.RegularExpressions;
using System.Xml;
using ValidationFramework.Extensions;
using ValidationFramework.Configuration.Xml;
using ValidationFramework.Configuration;

namespace ValidationFramework.Specifications
{
    /// <summary>
    /// A <see cref="IRuleConfigReader"/> that creates a <see cref="Rule"/> from a <see cref="XmlElement"/>.
    /// </summary>
    /// <remarks>
    ///   <b>Attributes</b>
    ///   <ul>
    ///     <li>
    ///       <c>validationExpression</c> (required): Used to populate <see cref="ValidationFramework.RegexRule.ValidationExpression"/>.   
    ///     </li>
    ///     <li>
    ///       <c>regexOptions</c> (optional): Used to populate <see cref="ValidationFramework.RegexRule.RegexOptions"/>.   
    ///     </li>
    ///   </ul>
    /// </remarks>
    /// <example>
    /// <code lang="xml" title="This example shows an xml configuration for RegexRuleConfigReader. The RegexRule generated will validate an email address.">
    /// <rule 
    /// validationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" 
    /// errorMessage="hello" 
    /// typeName="RegexRule" 
    /// regexOptions="RightToLeft"/>
    /// </code>
    /// </example>
    /// <seealso cref="RegexRule"/>
    /// <seealso cref="ConfigurationService"/>
    public sealed class MatchesRegexParser : ISpecificationXmlParser
    {
		public ISpecification GetSpecification(XmlElement SpecificationElement, RuleContext context)
        {
            Guard.ArgumentNotNull(SpecificationElement, "SpecificationElement");
            var regexOptions = SpecificationElement.GetAttribute("regexOptions", RegexOptions.None);
            var regexExpression = SpecificationElement.GetAttribute<string>("validationExpression");

            Guard.ArgumentNotNullOrEmptyString(regexExpression, "validationExpression");

            return new MatchesRegexSpec(regexExpression, regexOptions);
        }
    }
}